package com.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.common.Constants;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService extends ServiceImpl<UserMapper,User> {
    @Autowired
    private UserMapper userMapper;

    public User login(User user){
        User one=getUserInfo(user);
        if(one!=null){
            return user;
        }
        else throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
    }

    public boolean saveUser(User user) {
        if(user.getUname()==null)
            return save(user);//serviceimpl自带的
        else return userMapper.update(user);
    }

    public User register(User user) {
        User one=getUserInfo(user);
        if(one==null)
        {
            save(user);
        }else{
            throw new ServiceException(Constants.CODE_600,"用户已存在");
        }
        return user;
    }
    private User getUserInfo(User user){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uname",user.getUname());
        queryWrapper.eq("pwd",user.getPwd());
        User one;
        try {
            one=getOne(queryWrapper);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }
}
